<!--
 * @Description: file content
 * @Version: 2.0
 * @Autor: LYS
 * @Date: 2024-08-30 10:22:20
 * @LastEditors: LYS
 * @LastEditTime: 2024-11-11 14:54:46
-->
<template>
    <div style="width: 100%; height: 100%; position: relative">
        <canvas ref="animationCanvas" style="width: 100%; height: 100%"></canvas>
        <canvas ref="cRef2" style="width: 100%; height: 100%"></canvas>
    </div>
</template>

<script>
import axios from "axios";
import CustomLoading from "@/components/CustomLoading.vue";

export default {
    name: "WebsocketImagePlayer",
    components: {
        CustomLoading,
    },
    props: {
        // siteId是一个预期接收的属性
        accAddressId: {
            type: Number,
            required: false,
        },
    },
    data() {
        return {
            vId: "",
            context: null,
            imageSrc: "",
            websocket: null,
            worker: null,
            isLoading: true,
        };
    },
    watch: {
        accAddressId(newValue, oldValue) {
            console.log("视频重新加载", newValue);
            // 切视频时无缝切换，不产生黑场。只在某些插件实现了该行为才起作用
            this.sendStreamAddress(newValue);
        },
    },
    methods: {
        // 抽象出获取URL的方法
        async sendStreamAddress(id = this.accAddressId) {
            try {
                let url;
                url = `http://127.0.0.1:9998/startVideo?rtsp=rtsp://admin:password@192.168.100.20:554/Streaming/Channels/102&id=121`;
                // 使用axios发起GET请求
                const response = await axios.get(url);
                console.log(response, "response");

                this.vId = response.data.msg || "";
                this.$emit("stopVideoIdEvent", this.vId);
                console.log(this.vId, "vId");

                // 请求成功后处理响应数据
            } catch (error) {
                // 处理请求失败的情况
                console.error("Error stopping video stream:", error);
            }
        },
        webSocketInit() {
            if (!("WebSocket" in window)) {
                console.error("WebSocket 不被支持");
                return;
            }
            let wsUrl;
            if (process.env.NODE_ENV === "production") {
                wsUrl = `ws://192.168.100.192:9998/webSocketService`;
            } else {
                wsUrl = `ws://127.0.0.1:9998/webSocketService`;
            }
            this.websocket = new WebSocket(wsUrl);
            this.websocket.onopen = () => {
                console.log("成功连接到服务器");
            };
            this.websocket.onmessage = (event) => {
                console.log("服务器返回", event);

                let d = JSON.parse(event.data);
                this.drawFrame(d.data);
            };
            this.websocket.onerror = (event) => {
                console.error("WebSocket 连接发生错误", event);
            };

            this.websocket.onclose = () => {
                console.log("WebSocket 连接关闭");
            };
        },
        drawFrame(base64Data) {
            let img = new Image();
            img.src = `data:image/*;base64,${base64Data.base64Image}`;
            img.onload = () => {
                //关闭loading
                this.isLoading = false;
                //适应设备像素比:
                const ratio = window.devicePixelRatio || 1;
                this.$refs.animationCanvas.width =
                    this.$refs.animationCanvas.clientWidth * ratio;
                this.$refs.animationCanvas.height =
                    this.$refs.animationCanvas.clientHeight * ratio;
                // this.context.scale(ratio, ratio);
                //属性设置为 false 可能会减少模糊效果，
                this.context.imageSmoothingEnabled = false;
                // 按照原始尺寸绘制图像，或者根据需要调整
                this.context.drawImage(
                    img,
                    0,
                    0,
                    this.context.canvas.width,
                    this.context.canvas.height
                );
            };
        },
        async handleBeforeUnload() {
            try {
                // 定义API的URL
                const url = `http://192.168.100.192:9998/stopVideo`;
                // 使用axios发起GET请求
                const response = await axios.get(url);
                // 请求成功后处理响应数据
                console.log(response);
            } catch (error) {
                // 处理请求失败的情况
                console.error("Error stopping video stream:", error);
            }
        },
    },
    async mounted() {
        window.addEventListener("beforeunload", this.handleBeforeUnload);
        this.context = this.$refs.animationCanvas.getContext("2d");
        await this.sendStreamAddress();
        this.webSocketInit();
    },
    beforeDestroy() {
        if (this.websocket) {
            this.websocket.close();
        }
    },
};
</script>

<style scoped>
.loading {
    position: absolute;
    left: 50%;
    top: 50%;
    -webkit-transform: translate(-50%, -50%);
    transform: translate(-50%, -50%);
}

/* 你可以在这里添加样式 */
</style>
